export let auth = {
	userinfo: null,
	ready: false,
	
	keys: {
		storageToken: 'x-token',
		storageUserInfo: 'x-userinfo',
		// eventHadLogin: 'x-event-auth-had-login',
		// eventForceLogin: 'x-event-auth-force-login',
		eventLogined: 'x-event-auth-logined',
		eventLogouted: 'x-event-auth-logouted',
		eventUserInfo: 'x-event-auth-userinfo',
	},

	checkLogin() {
		let ret = auth.isLogin()
		if(ret) uni.$emit(auth.keys.eventLogined)
		return ret
	},
	logined(data) {
		auth.setToken(data)
		setTimeout(()=>uni.$emit(auth.keys.eventLogined, data), 50)
	},
	logouted(invalidate) {
		auth.clear(invalidate)
		setTimeout(()=>uni.$emit(auth.keys.eventLogouted), 50)
	},

	getUserInfo() {
		if(auth.userinfo) return auth.userinfo
		return auth.userinfo = uni.getStorageSync(auth.keys.storageUserInfo)
	},
	setUserInfo(user) {
		auth.userinfo = user
		uni.setStorageSync(auth.keys.storageUserInfo, user)
		this.ready = true
		uni.$emit(auth.keys.eventUserInfo)
		return user
	},
	clearUserInfo() {
		auth.userinfo = null
		return uni.removeStorage({key: auth.keys.storageUserInfo})
	},

	getToken() {
		return uni.getStorageSync(auth.keys.storageToken)
	},
	setToken(token) {
		return uni.setStorageSync(auth.keys.storageToken, token)
	},
	clearToken() {
		return uni.removeStorage({key: auth.keys.storageToken})
	},
	clear(invalidate) {
		auth.clearToken()
		auth.clearUserInfo()
	},

	getUserId() {
		const res = auth.getUserInfo() || {}
		return res.userId || res.id
	},
	isLogin(forceLogin) {
		let ret = Boolean(uni.$x.auth.getToken())
		if(!ret&&forceLogin) uni.$x.navigator.goLogin()
		return ret
	},
}


export default function($x, {
	authKeyExtend, authExtend
}={}, app) {
	Object.assign(auth, authExtend||{})
	Object.assign(auth.keys, authKeyExtend||{})
	$x.auth = auth
}
